Collections And Enumerables
🧠📚 Collection Interfaces — Deep Dive with Examples
---
- IEnumerable
— Read-Only Forward Iteration - ICollection
— Countable, Modifiable Collections - IList
— Indexed Access Collections - IReadOnlyCollection
& IReadOnlyList — Immutable Access - IQueryable
— Expression Trees for Remote Queries
---
Questions & Answers
Q: Why should I return IEnumerable
A: IEnumerable
Q: When should I use ICollection
A: When you need Count without enumerating everything, or when callers need Add/Remove. Trading systems use ICollection
Q: What's the performance difference between IEnumerable
A: IList
Q: How does IQueryable
A: IQueryable
Q: Should I return IReadOnlyCollection
A: IReadOnlyCollection
Q: What happens if I call .ToList() on every IEnumerable
A: You materialize the entire sequence into memory immediately, losing lazy evaluation benefits. This hurts performance with large datasets and breaks streaming scenarios.
Q: How do these interfaces relate to LINQ?
A: LINQ methods extend IEnumerable
Q: Can I cast IEnumerable
A: Not always. Use source as List<T> for null-safe casting, but prefer enumeration. Casting breaks abstraction and assumes implementation details callers shouldn't know.
Q: How do collection interfaces improve testability?
A: Accepting IEnumerable
Q: What's the memory impact of yielding with IEnumerable
A: Iterator blocks (yield return) create state machines that produce items on demand, reducing peak memory. This is critical for processing large datasets or infinite sequences.